package com.ea.admin.service.impl;

import cn.hutool.core.util.IdUtil;
import com.ea.admin.mapper.AdminAccountMapper;
import com.ea.admin.mapper.DeptInfoMapper;
import com.ea.admin.pojo.Enum.RoleCode;
import com.ea.admin.service.*;
import com.ea.common.report.ReportFeign;
import com.ea.common.report.pojo.param.GetDashboardVoParam;
import com.ea.common.report.pojo.vo.DashboardVo;
import com.ea.common.result.BizException;
import com.ea.common.result.ErrorCode;
import com.ea.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Service
public class SseServiceImpl implements SseService {
    /**
     * messageId的 SseEmitter对象映射集
     * key 为 clientId (唯一)
     */
    public static Map<String, SseData> sseDataMap = new ConcurrentHashMap<>();
    @Resource
    CompanyPermissionService companyPermissionService;
    @Resource
    DeptPermissionService deptPermissionService;
    @Resource
    PermissionService permissionService;
    @Resource
    DepartmentService departmentService;
    @Resource
    AdminAccountMapper adminAccountMapper;
    @Resource
    DeptInfoMapper deptInfoMapper;
    @Resource
    ReportFeign reportFeign;

    /**
     * 连接sse
     */
    @Override
    public SseEmitter connect(Long userId) {
        String clientId = IdUtil.fastSimpleUUID();
        SseEmitter sseEmitter = new SseEmitter(0L);
        // 连接成功需要返回数据，否则会出现待处理状态
        // 返回uuid
        //sseEmitter.send(userId, MediaType.APPLICATION_JSON);
        // 使用子线程发送消息，避免阻塞主线程
        new Thread(() -> {
            sendMessage(userId, clientId, sseEmitter);
        }).start();

        log.info("连接成功，userId:{}, clientId:{}", userId, clientId);

        // 连接断开
        sseEmitter.onCompletion(() -> {
            log.info("连接完成，userId:{}, clientId:{}", userId, clientId);
            sseDataMap.remove(clientId);
        });

        // 连接超时
        sseEmitter.onTimeout(() -> {
            log.info("连接超时，userId:{}, clientId:{}", userId, clientId);
            sseDataMap.remove(clientId);
        });

        // 连接报错
        sseEmitter.onError((throwable) -> {
            log.info("连接出错，userId:{}, clientId:{}", userId, clientId);
            sseDataMap.remove(clientId);
        });

        SseData sseData = new SseData();
        sseData.setUserId(userId);
        sseData.setClientId(clientId);
        sseData.setSseEmitter(sseEmitter);
        sseDataMap.put(clientId, sseData);

        return sseEmitter;
    }

    /**
     * 发送消息
     */
    @Override
    public void sendMessage(Long userId, String clientId, SseEmitter sseEmitter) {
        try {
            // 随便一个超级管理员的id
//            LambdaQueryWrapper<AdminAccount> wrapper = new LambdaQueryWrapper<>();
//            wrapper.eq(AdminAccount::getAdminRoleId, 1);
//            wrapper.last("limit 1");
//            AdminAccount adminAccount = adminAccountMapper.selectOne(wrapper);
//            Long accountId = adminAccount.getAccountId();

            List<Long> companyIdList = null;
            List<Long> deptIdList = null;
//            String startDate = null;
//            String endDate = null;
            // 查询用户权限
            PermissionServiceImpl.PermissionList checked = permissionService
                    .checkAndRefreshPermissionList(companyIdList, deptIdList, userId);
            companyIdList = checked.companyIdList;
            deptIdList = checked.deptIdList;
            Long adminRoleId = adminAccountMapper.selectById(userId).getAdminRoleId();

            // 查出所有下级单位
            List<Long> queryCompanyIdList = companyPermissionService.getSubCompanyIdList(userId, companyIdList);

            // 查出所有下级部门
            List<Long> queryDeptIdList ;
            // 部门管理员对应部门查询,单位以上层级管理员赋予以下所有部门权限
            if(adminRoleId== RoleCode.DEPT_SUPER_ADMIN.getCode().longValue()||
                    adminRoleId== RoleCode.DEPT_ADMIN.getCode().longValue()) {
                // 查出所有下级部门
                queryDeptIdList = deptPermissionService.getSubDepartmentIdList(userId, companyIdList, deptIdList);
            }else{
                queryDeptIdList =deptInfoMapper.getAllByCompanyId(queryCompanyIdList);
            }

            // 获取部门的总人数分男女
            Integer totalCount = departmentService.getTotalCount(queryDeptIdList);
            Integer totalCountFemale=deptInfoMapper.getTotalFemaleCount(queryDeptIdList);
            Integer totalCountMale=totalCount-totalCountFemale;
            Result<DashboardVo> result = reportFeign.getDashboardVo(new GetDashboardVoParam(queryCompanyIdList, queryDeptIdList, totalCount,
                    totalCountFemale,totalCountMale,null, null));
            if (result == null || result.getData() == null || result.getCode() != ErrorCode.NO_ERROR.getCode()) {
                throw new BizException(ErrorCode.TPS_DOWNSTREAM_SERVICE_ERROR);
            }

            DashboardVo message = result.getData();
            log.info("发送消息给用户:{}", userId);
            sseEmitter.send(message, MediaType.APPLICATION_JSON);
        } catch (Exception ignored) {
        }
    }

    @Override
    public void closeSseConnect(String clientId) {
        SseData sseData = sseDataMap.get(clientId);
        SseEmitter sseEmitter = sseData.getSseEmitter();
            sseEmitter.complete();
            sseDataMap.remove(clientId);
    }

}

